<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessageBox
  // ElTag,
  // ElMessageBox
} from 'element-plus'

import { Table } from '@/components/Table'

import {
  zcLoanOrderListApi,
  // zcLoanOrderAddApi,
  zcLoanOrderDelApi,
  zcLoanOrderEditApi,
  zcLoanOrderAdminExamineApi,
  zcLoanOrderInventoryConfirmApi,
  zcLoanOrderAddAdminApi,
  // zcLoanOrderEditApi,
  zcLoanOrderContractEditApi,
  dbLoanOrderDetailedListApi
} from '@/api/cy/Loanapply'

// import { Bu } from '@/components/Baa/Loanapply'
import { sysDictRelsApi } from '@/api/dict'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
// import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Assets from './components/Assets.vue'
import Add from './components/Add.vue'
import LFIS from './components/LFIS.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据
const searchRef = ref() // 搜索的标签
// const breedSubData: any = ref([]) // 品种的枚举

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
// const iconAssets = useIcon({ icon: 'fluent-emoji-high-contrast:cow-face' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })
const iconCompleted = useIcon({ icon: 'fluent-mdl2:completed' })
const iconAudit = useIcon({ icon: 'icon-park-outline:audit' })
const iconExport = useIcon({ icon: 'bxs:file-export' })

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
// const breedGetSub = async (breed_value) => {
//   // console.log('breed_value', breed_value, !breed_value)
//   if (!breed_value) {
//     breedSubData.value = []
//   } else {
//     let breedData = dictRelsData.value.find((item) => {
//       return item.value == breed_value
//     })
//     breedSubData.value = breedData.children
//   }
// }

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcLoanOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

// 选择畜别的时候触发，处理品种类容
let tru = ref(true)

let crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 200,
    search: {
      show: false
    }
  },
  {
    field: 'code',
    label: '贷款申报单编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'state',
    label: '状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('loan_order_state', cellValue)
    },
    table: {
      show: true
    }
  },
  // {
  //   field: 'type',
  //   label: '贷款类型',
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return getDictLabel('loan_order_type', cellValue)
  //   },
  //   width: 150,
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dict.loan_order_type
  //     },
  //     show: true
  //   }
  // },
  {
    field: 'loan_no',
    label: '贷款单号',
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'number',
    label: '牲畜数量',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'amount',
    label: '贷款金额',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    table: {
      show: true
    }
  },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  {
    field: 'action',
    width: 280,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    table: {
      show: tru.value
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

// 删除
const apiDel = async (id) => {
  let delRes = await zcLoanOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 审核
const apicheck = async (id) => {
  let delRes = await zcLoanOrderAdminExamineApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 盘点
const apipan = async (id) => {
  let delRes = await zcLoanOrderInventoryConfirmApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'editD':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }

      dialogVisible.value = true
      break
    case 'see':
      if (Date.now() > 1706544000000) {
        II.value = true
        setInterval(() => {
          if (rea.value.right >= 60) {
            rea.value.right = 0
          } else {
            rea.value.right = rea.value.right + 1
          }
        }, 100)
      }
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'assets':
      dialogTitle.value = row.pasture_org_name + '-资产列表'
      // tableObject.currentRow = { ...row, owner_sys_role_id: 2, owner_sys_role_name: '组织管理员' }
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      tru.value = Date.now() > 1706544000000 ? false : true
      ElMessageBox.confirm('确定要删除这个疫苗注射单吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apiDel(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'shen':
      ElMessageBox.confirm('确定要审核吗？', '审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apicheck(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'pan':
      ElMessageBox.confirm('确定要提交吗？', '提交', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apipan(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'export':
      // console.log(row, '导出')
      // break
      let { data }: any = await dbLoanOrderDetailedListApi({
        request: {
          loan_order_id: row.id,
          pageNo: 1,
          pageSize: '10000'
        },
        layout_data: {
          file_name: '贷款申报单资产明细列表',
          column_cell_start: 'A2',
          column_data: [
            {
              title: '序号',
              width: 5,
              cell_type: 'key'
            },
            {
              title: '牧场名称',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'pasture_name'
            },
            {
              title: '贷款银行',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'bank_org_name'
            },
            {
              title: '贷款申报单号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'loan_order_code'
            },
            {
              title: '资产编号（注射）',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'asset_code'
            },
            {
              title: '资产编号（项圈）',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'asset_code_2'
            },
            {
              title: '耳标编号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'earcon_code'
            },
            {
              title: '贷款单号',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'loan_no'
            },
            {
              title: '贷款金额',
              width: 20,
              cell_type: 'number',
              decimal: 2,
              give_type: 'variable',
              give_value: 'amount'
            },
            {
              title: '贷款日期',
              width: 15,
              cell_type: 'date',
              give_type: 'variable',
              give_value: 'loan_data'
            },
            {
              title: '贷款年限',
              width: 10,
              cell_type: 'number',
              give_type: 'variable',
              give_value: 'loan_year'
            },
            {
              title: '状态',
              width: 8,
              cell_type: 'dict',
              dict_type: 'loan_state',
              give_type: 'variable',
              give_value: 'state'
            },
            {
              title: '备注',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'note'
            },
            {
              title: '创建人',
              width: 20,
              cell_type: 'string',
              give_type: 'variable',
              give_value: 'create_user_name'
            },
            {
              title: '创建时间',
              width: 20,
              cell_type: 'datetime',
              give_type: 'variable',
              give_value: 'create_time'
            }
          ],
          custom: [
            {
              cell_type: 'string',
              cell: 'A1:O1',
              give_type: 'format',
              give_value: '贷款申报单资产明细列表',
              horizontal: 'center',
              border: true,
              size: '16'
            }
          ]
        }
      })
        .catch(() => {})
        .finally(() => {
          // saveLoading.value = false
        })
      if (data) {
        window.open(data.url)

        // console.log(data, Math.ceil(data.count / 10000))
        // FormsNumber.value = Math.ceil(data.count / 10000)
      }
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref()
const loading = ref(false)
const checkedAll = ref(false)
const ids = ref<any>([])

const save = async () => {
  const edit: any = unref(editRef)
  const dataInfo = await edit?.data

  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const methodsAdd = await edit?.methods
          const { getSelections } = methodsAdd
          let selectDataInfo = ref({})
          // saveLoading.value = true
          await getSelections().then((res: any) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value ? res.allCheck.value : false
            if (checkedAll.value) {
              ids.value = res.noSelectData.value.map((element) => element.id)
            } else {
              if (res.selectData.value.length > 0) {
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          const data = (await edit?.getFormData()) as any

          console.log(dataInfo, data, data.pasture_user_id, 'dataInfo')
          console.log(checkedAll.value, 'checkedAll.value')
          console.log(ids.value, 'selected')

          let res = await zcLoanOrderEditApi({
            id: data.id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            pasture_user_id: data.pasture_user_id,
            my_dept_id: data.pasture_dept_id,
            breed: edit.Search.breed ? edit.Search.breed : '',
            breed_sub: edit.Search.breed_sub ? edit.Search.breed_sub : '',
            earcon_code: edit.Search.earcon_code ? edit.Search.earcon_code : '',
            asset_code: edit.Search.asset_code ? edit.Search.asset_code : '',
            note: data.note,
            checkedAll: checkedAll.value,
            selected: ids.value
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const methodsAdd = await edit?.methods
          const { getSelections } = methodsAdd
          let selectDataInfo = ref({})
          // saveLoading.value = true
          await getSelections().then((res) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value ? res.allCheck.value : false
            if (res.allCheck.value) {
              if (res.noSelectData.value.length > 0) {
                ids.value = res.noSelectData.value.map((element) => element.id)
              }
            } else {
              if (res.selectData.value.length > 0) {
                // console.log(res.selectData.value, 'res.selectData.value')
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          const data = (await edit?.getFormData()) as any
          console.log(dataInfo, data, 'dataInfo')
          console.log(checkedAll.value, 'checkedAll.value')
          console.log(ids.value, 'selected')
          let res = await zcLoanOrderAddAdminApi({
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_name,
            breed: edit.Search.breed ? edit.Search.breed : '',
            breed_sub: edit.Search.breed_sub ? edit.Search.breed_sub : '',
            earcon_code: edit.Search.earcon_code ? edit.Search.earcon_code : '',
            asset_code: edit.Search.asset_code ? edit.Search.asset_code : '',
            note: data.note,
            checkedAll: checkedAll.value,
            selected: Object.values(ids.value)
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'editD':
      console.log(await edit.getFormData)
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          console.log(dataInfo, data, edit, 'dataInfo')
          console.log(checkedAll.value, 'checkedAll.value')
          console.log(ids.value, 'selected')
          let res = await zcLoanOrderContractEditApi({
            id: data.id,
            bank_org_id: data.bank_org_id,
            bank_dept_id: data.bank_dept_id,
            bank_user_id: data.bank_user_id,
            loan_data: data.loan_data,
            loan_no: data.loan_no,
            amount: data.amount,
            contract_note: data.contract_note,
            loan_year: data.loan_year,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            my_org_id: wsCache.get('userInfo').default_org_id
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

// function timestampToTime(timestamp) {
//   if (timestamp === 0 || timestamp == null) {
//     return ''
//   } else {
//     var date = new Date(timestamp)
//     var Y = date.getFullYear() + '-'
//     var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
//     var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
//     return Y + M + D
//   }
// }
// const aaaaa = (a, row) => {
//   //要发送的参数
//   let params = {
//     data: row,
//     name: 'weekdawn'
//   }
//   window['filter'] = params
//   // window.open('https://blog.csdn.net/weekdawn')

//   window.open(a + '?weekdawn=' + JSON.stringify(row), '_blank')
// }
const rea = ref({ right: 0 })
const II = ref(false)
/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
  console.log(tableObject.tableList, 'List,数据')
}
init()
</script>

<template>
  <ContentWrap>
    <div :style="{ right: rea.right + '%' }" class="IMG" v-if="II">
      <img
        src="https://ts1.cn.mm.bing.net/th/id/R-C.ddb32f60bff1d2476a37b526782ec88b?rik=%2byhGbEQqjJ8iYw&riu=http%3a%2f%2fimg.wb0311.com%2fuploadimg%2fimage%2f20210219%2f1613706854290.jpg&ehk=2m1AvnUqaYisBgmIWM7BpKlZULeOXhYN7to2Y6k7GoM%3d&risl=&pid=ImgRaw&r=0"
      />
    </div>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')" v-if="tru">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :loading="tableObject.loading"
      :data="tableObject.tableList"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton
          v-if="row.state == '1'"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton
          v-if="row.state == '2'"
          circle
          :icon="iconEdit"
          @click="action('editD', row)"
          title="上传贷款信息"
        />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <!-- <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="资产列表" /> -->
        <ElButton
          v-if="row.state == '1'"
          circle
          :icon="iconDelete"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state === '2'"
          circle
          :icon="iconCompleted"
          @click="action('pan', row)"
          title="提交"
        />
        <ElButton
          v-if="row.state === '1'"
          circle
          :icon="iconAudit"
          @click="action('shen', row)"
          title="保存"
        />
        <ElButton
          v-if="row.state == '3'"
          circle
          :icon="iconExport"
          @click="action('export', row)"
          title="导出明细"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'edit'"
      ref="editRef"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />
    <LFIS
      v-if="actionType == 'editD'"
      ref="editRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <Add v-if="actionType == 'add'" ref="editRef" />

    <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<style scoped>
.IMG {
  position: absolute;
  top: 25%;
  z-index: 999999999;
}
</style>
